package com.ivo.activiti.controller;

import com.ivo.activiti.bpmn.ProcessService;
import com.ivo.activiti.entity.Diagram;
import com.ivo.activiti.entity.ProcessDiagram;
import com.ivo.activiti.service.ProcessDiagramService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 流程图接口
 * @author wj
 * @version 1.0
 */
@RestController
@RequestMapping("processDiagram")
public class ProcessDiagramController {

    @Resource
    private ProcessDiagramService processDiagramService;

    /**
     * 获取流程图
     * @param diagramId ID
     */
    @GetMapping("/diagram")
    public void diagram(long diagramId, HttpServletResponse response) {
        Diagram diagram = processDiagramService.getDiagram(diagramId);
        if(diagram == null) return;
        // 输出流程图
        byte[] xml = diagram.getXml();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(xml);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存流程图
     * @param id ID
     * @param name NAME
     * @param businessKey businessKey
     * @param xml xml
     */
    @PostMapping("/saveDiagram")
    public String saveDiagram(Long id, String name, String businessKey, String xml) {
        ProcessDiagram processDiagram = null;
        if(id != null) processDiagram = processDiagramService.getProcessDiagram(id);
        if(processDiagram == null) processDiagram = new ProcessDiagram();
        processDiagram.setName(name);
        processDiagram.setBusinessKey(businessKey);
        processDiagram.setDeploy(false);
        Diagram diagram = processDiagramService.getDiagram(processDiagram.getDiagramId());
        if(diagram == null) diagram = new Diagram();
        byte[] bytes = xml.getBytes(StandardCharsets.UTF_8);
        diagram.setXml(bytes);
        processDiagramService.saveDiagram(diagram);
        processDiagram.setDiagramId(diagram.getId());
        processDiagramService.saveProcessDiagram(processDiagram);
        return "ok";
    }

    /**
     * 流程图列表
     */
    @GetMapping("/list")
    public List<ProcessDiagram> processDiagram() {
        return processDiagramService.getProcessDiagram();
    }

    /**
     * 流程图列表
     */
    @GetMapping("/getOne")
    public ProcessDiagram processDiagram(Long id) {
        return processDiagramService.getProcessDiagram(id);
    }

    /**
     * 部署流程图
     * @param id 流程图ID
     */
    @RequestMapping("/deploy")
    public String deploy(Long id) {
        processDiagramService.deployProcessDiagram(id);
        return "ok";
    }
}
